package cn.com.guage.dtm.huawei;

import java.util.*;
import java.util.stream.Collectors;

public class guage_权重计算器 {
    public static void  main(String[] args) {
        Map<String, Integer> weights = new HashMap<>();
        weights.put("a", 10);
        weights.put("b", 20);
        weights.put("c", 30);

        WeightCalculator calculator = new WeightCalculator(weights);
        int[] counts = new int[3];
        int total = 60000;

        for (int i = 0; i < total; i++) {
            String res = calculator.fetchCalcResult();
            switch (res) {
                case "a":
                    counts[0]++;
                    break;
                case "b":
                    counts[1]++;
                    break;
                case "c":
                    counts[2]++;
                    break;
            }
        }
    }

    static class WeightCalculator {
        private final List<String> keys;
        private final int[] cumulativeWeights;
        private final int totalWeight;
        private final Random random;

        public WeightCalculator(Map<String, Integer> weights) {
            List<Map.Entry<String, Integer>> validEntries = weights.entrySet().stream()
                    .filter(entry -> entry.getValue() > 0)
                    .collect(Collectors.toList());

            if (validEntries.isEmpty()) {
                throw new IllegalArgumentException("至少需要一个权重大于0的键");
            }

            this.keys = new ArrayList<>();
            List<Integer> cumulative = new ArrayList<>();
            int currentSum = 0;

            for (Map.Entry<String, Integer> entry : validEntries) {
                currentSum += entry.getValue();
                cumulative.add(currentSum);
                keys.add(entry.getKey());
            }

            this.totalWeight = currentSum;
            this.cumulativeWeights = cumulative.stream().mapToInt(Integer::intValue).toArray();
            this.random = new Random();
        }

        public String fetchCalcResult() {
            if (keys.isEmpty()) {
                throw new IllegalStateException("没有可用的键");
            }

            int randomValue = random.nextInt(totalWeight);
            int index = Arrays.binarySearch(cumulativeWeights, randomValue);

            if (index < 0) {
                index = -index - 1;
            } else {
                index++;
            }

            // 确保索引不超过数组范围
            if (index >= cumulativeWeights.length) {
                index = cumulativeWeights.length - 1;
            }

            return keys.get(index);
        }
    }
}